/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved.
 */

package com.kelai.common;

import javafx.util.Callback;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.util.StringUtils;
import com.kelai.common.exception.BreezeeException;

/**
 * 数据持久化的基类
 * Created by Silence on 2016/6/5.
 */
@SuppressWarnings("unchecked")
@NoRepositoryBean
public interface IRepository<T extends PersistObject> extends JpaRepository<T, String>, JpaSpecificationExecutor<T> {

    default T saveEntity(T t, Callback<T, Object>... callback) throws BreezeeException {
        T old;
        if (StringUtils.isEmpty(t.getId())) {
            if (StringUtils.hasText(t.getCode())) {
                old = this.findByCode(t.getCode());
                if (old != null) throw new BreezeeException("code:" + t.getCode() + "已经存在");
            }
        } else {
            old = this.findOne(t.getId());
            if (old == null) throw new BreezeeException(t.getClass().getName() + "@" + t.getId() + " does not exist");
        }
        for (Callback<T, ?> rCallback : callback) {
            try {
                rCallback.call(t);
            } catch (Exception e) {
                e.printStackTrace();
                throw new BreezeeException(e.getMessage(), e);
            }
        }
        try {
            this.saveAndFlush(t);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BreezeeException(e.getMessage(), e);
        }
        return t;
    }

    T findByCode(String code);
}
